<template>
  <div class="coding-home">
    <!-- 欢迎横幅 -->
    <div class="welcome-banner">
      <div class="banner-content">
        <div class="welcome-text">
          <h1>编程实战平台</h1>
          <p>提升编程技能，挑战算法难题，成为编程高手</p>
        </div>
        <div class="banner-stats">
          <div class="stat-item">
            <div class="stat-number">{{ stats.totalProblems }}</div>
            <div class="stat-label">编程题目</div>
          </div>
          <div class="stat-item">
            <div class="stat-number">{{ stats.totalUsers }}</div>
            <div class="stat-label">活跃用户</div>
          </div>
          <div class="stat-item">
            <div class="stat-number">{{ stats.totalSubmissions }}</div>
            <div class="stat-label">代码提交</div>
          </div>
        </div>
      </div>
    </div>

    <!-- 快速入口 -->
    <div class="quick-actions">
      <div class="action-grid">
        <div class="action-card" @click="goToProblemList">
          <div class="action-icon">
            <el-icon><Document /></el-icon>
          </div>
          <div class="action-content">
            <h3>刷题练习</h3>
            <p>海量算法题目等你挑战</p>
          </div>
        </div>
        
        <div class="action-card" @click="goToMySubmissions">
          <div class="action-icon">
            <el-icon><User /></el-icon>
          </div>
          <div class="action-content">
            <h3>我的提交</h3>
            <p>查看提交记录和解题进度</p>
          </div>
        </div>
        
        <div class="action-card" @click="goToLeaderboard">
          <div class="action-icon">
            <el-icon><Trophy /></el-icon>
          </div>
          <div class="action-content">
            <h3>排行榜</h3>
            <p>查看全站编程高手排名</p>
          </div>
        </div>
        
        <div class="action-card" @click="startRandomProblem">
          <div class="action-icon">
            <el-icon><Refresh /></el-icon>
          </div>
          <div class="action-content">
            <h3>随机一题</h3>
            <p>随机挑选题目开始练习</p>
          </div>
        </div>
      </div>
    </div>

    <!-- 推荐题目 -->
    <div class="featured-problems">
      <div class="section-header">
        <h2>推荐题目</h2>
        <el-button text @click="viewAllProblems">
          查看全部 <el-icon><ArrowRight /></el-icon>
        </el-button>
      </div>
      
      <div class="problems-grid">
        <div 
          v-for="problem in featuredProblems" 
          :key="problem.id"
          class="problem-card"
          @click="viewProblem(problem)"
        >
          <div class="problem-header">
            <div class="problem-difficulty">
              <el-tag :type="getDifficultyType(problem.difficulty)" size="small">
                {{ problem.difficulty }}
              </el-tag>
            </div>
            <div class="problem-tags">
              <el-tag 
                v-for="tag in problem.tags.slice(0, 2)" 
                :key="tag"
                size="small"
                effect="plain"
              >
                {{ tag }}
              </el-tag>
            </div>
          </div>
          
          <div class="problem-content">
            <h3 class="problem-title">{{ problem.title }}</h3>
            <p class="problem-desc">{{ problem.description }}</p>
            
            <div class="problem-meta">
              <div class="meta-item">
                <el-icon><User /></el-icon>
                <span>{{ problem.submissions }}人提交</span>
              </div>
              <div class="meta-item">
                <el-icon><CircleCheck /></el-icon>
                <span>{{ problem.acceptanceRate }}%通过率</span>
              </div>
            </div>
            
            <div class="problem-footer">
              <div class="problem-status" v-if="problem.userStatus">
                <el-tag 
                  :type="problem.userStatus === 'solved' ? 'success' : 'warning'" 
                  size="small"
                >
                  {{ problem.userStatus === 'solved' ? '已解决' : '尝试过' }}
                </el-tag>
              </div>
              <el-button type="primary" size="small" @click.stop="solveProblem(problem)">
                开始解题
              </el-button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 学习路径 -->
    <div class="learning-paths">
      <div class="section-header">
        <h2>学习路径</h2>
        <el-button text @click="viewAllPaths">
          查看全部 <el-icon><ArrowRight /></el-icon>
        </el-button>
      </div>
      
      <div class="paths-grid">
        <div 
          v-for="path in learningPaths" 
          :key="path.id"
          class="path-card"
          @click="viewPath(path)"
        >
          <div class="path-icon">
            <el-icon><Folder /></el-icon>
          </div>
          <div class="path-content">
            <h3 class="path-title">{{ path.title }}</h3>
            <p class="path-desc">{{ path.description }}</p>
            <div class="path-progress">
              <div class="progress-info">
                <span>进度：{{ path.progress }}/{{ path.total }}</span>
                <span>{{ Math.round(path.progress / path.total * 100) }}%</span>
              </div>
              <el-progress 
                :percentage="Math.round(path.progress / path.total * 100)" 
                :show-text="false"
                :stroke-width="6"
              />
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 最近提交 -->
    <div class="recent-submissions">
      <div class="section-header">
        <h2>最近提交</h2>
        <el-button text @click="viewAllSubmissions">
          查看全部 <el-icon><ArrowRight /></el-icon>
        </el-button>
      </div>
      
      <div class="submissions-list">
        <div 
          v-for="submission in recentSubmissions" 
          :key="submission.id"
          class="submission-item"
        >
          <div class="submission-info">
            <div class="problem-name">{{ submission.problemTitle }}</div>
            <div class="submission-time">{{ formatDate(submission.submittedAt) }}</div>
          </div>
          
          <div class="submission-details">
            <div class="language">{{ submission.language }}</div>
            <div class="status" :class="getStatusClass(submission.status)">
              {{ getStatusText(submission.status) }}
            </div>
            <div class="runtime" v-if="submission.runtime">
              {{ submission.runtime }}ms
            </div>
          </div>
          
          <div class="submission-actions">
            <el-button size="small" @click="viewSubmission(submission)">
              查看代码
            </el-button>
            <el-button size="small" type="primary" @click="retryProblem(submission)">
              重新提交
            </el-button>
          </div>
        </div>
      </div>
    </div>

    <!-- 编程竞赛 -->
    <div class="coding-contests">
      <div class="section-header">
        <h2>编程竞赛</h2>
        <el-button text @click="viewAllContests">
          查看全部 <el-icon><ArrowRight /></el-icon>
        </el-button>
      </div>
      
      <div class="contests-grid">
        <div 
          v-for="contest in upcomingContests" 
          :key="contest.id"
          class="contest-card"
        >
          <div class="contest-header">
            <div class="contest-status">
              <el-tag :type="getContestStatusType(contest.status)" size="small">
                {{ getContestStatusText(contest.status) }}
              </el-tag>
            </div>
            <div class="contest-time">
              {{ formatContestTime(contest.startTime) }}
            </div>
          </div>
          
          <div class="contest-content">
            <h3 class="contest-title">{{ contest.title }}</h3>
            <p class="contest-desc">{{ contest.description }}</p>
            
            <div class="contest-meta">
              <div class="meta-item">
                <el-icon><Clock /></el-icon>
                <span>{{ contest.duration }}分钟</span>
              </div>
              <div class="meta-item">
                <el-icon><Document /></el-icon>
                <span>{{ contest.problemCount }}题</span>
              </div>
              <div class="meta-item">
                <el-icon><User /></el-icon>
                <span>{{ contest.participants }}人参加</span>
              </div>
            </div>
            
            <div class="contest-footer">
              <el-button 
                :type="contest.status === 'upcoming' ? 'primary' : 'default'"
                size="small" 
                @click="joinContest(contest)"
                :disabled="contest.status === 'ended'"
              >
                {{ getContestButtonText(contest.status) }}
              </el-button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { 
  Document, User, Trophy, Refresh, ArrowRight, CircleCheck, 
  Folder, Clock
} from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'

const router = useRouter()

// 响应式数据
const stats = ref({
  totalProblems: '1000+',
  totalUsers: '50万+',
  totalSubmissions: '500万+'
})

const featuredProblems = ref([
  {
    id: 1,
    title: '两数之和',
    description: '给定一个整数数组和一个目标值，找出数组中和为目标值的两个数',
    difficulty: '简单',
    tags: ['数组', '哈希表'],
    submissions: 1250000,
    acceptanceRate: 49.2,
    userStatus: 'solved'
  },
  {
    id: 2,
    title: '反转链表',
    description: '反转一个单链表，可以迭代或递归地反转链表',
    difficulty: '简单',
    tags: ['链表', '递归'],
    submissions: 980000,
    acceptanceRate: 68.5,
    userStatus: 'attempted'
  },
  {
    id: 3,
    title: '最长回文子串',
    description: '给定一个字符串，找到其中最长的回文子串',
    difficulty: '中等',
    tags: ['字符串', '动态规划'],
    submissions: 750000,
    acceptanceRate: 32.1,
    userStatus: null
  },
  {
    id: 4,
    title: '合并K个升序链表',
    description: '给你一个链表数组，每个链表都已经按升序排列',
    difficulty: '困难',
    tags: ['链表', '分治', '堆'],
    submissions: 420000,
    acceptanceRate: 47.8,
    userStatus: null
  }
])

const learningPaths = ref([
  {
    id: 1,
    title: '数据结构基础',
    description: '掌握数组、链表、栈、队列等基础数据结构',
    progress: 8,
    total: 15
  },
  {
    id: 2,
    title: '算法入门',
    description: '学习排序、搜索、递归等基础算法',
    progress: 5,
    total: 12
  },
  {
    id: 3,
    title: '动态规划',
    description: '掌握动态规划的思想和经典问题',
    progress: 2,
    total: 10
  }
])

const recentSubmissions = ref([
  {
    id: 1,
    problemTitle: '两数之和',
    language: 'JavaScript',
    status: 'accepted',
    runtime: 68,
    submittedAt: new Date('2024-01-15')
  },
  {
    id: 2,
    problemTitle: '反转链表',
    language: 'Python',
    status: 'accepted',
    runtime: 52,
    submittedAt: new Date('2024-01-14')
  },
  {
    id: 3,
    problemTitle: '最长回文子串',
    language: 'Java',
    status: 'wrong_answer',
    runtime: null,
    submittedAt: new Date('2024-01-13')
  }
])

const upcomingContests = ref([
  {
    id: 1,
    title: '周赛 380',
    description: '每周定期举办的编程竞赛，适合各个水平的程序员',
    status: 'upcoming',
    startTime: new Date('2024-01-20 10:30:00'),
    duration: 90,
    problemCount: 4,
    participants: 15000
  },
  {
    id: 2,
    title: '算法专题赛',
    description: '专注于动态规划和贪心算法的专题竞赛',
    status: 'ongoing',
    startTime: new Date('2024-01-15 14:00:00'),
    duration: 120,
    problemCount: 5,
    participants: 8500
  }
])

// 方法
const getDifficultyType = (difficulty) => {
  const types = {
    '简单': 'success',
    '中等': 'warning',
    '困难': 'danger'
  }
  return types[difficulty] || 'info'
}

const getStatusClass = (status) => {
  const classes = {
    'accepted': 'success',
    'wrong_answer': 'error',
    'time_limit_exceeded': 'warning'
  }
  return classes[status] || 'default'
}

const getStatusText = (status) => {
  const texts = {
    'accepted': '通过',
    'wrong_answer': '答案错误',
    'time_limit_exceeded': '超时'
  }
  return texts[status] || '未知'
}

const getContestStatusType = (status) => {
  const types = {
    'upcoming': 'warning',
    'ongoing': 'success',
    'ended': 'info'
  }
  return types[status] || 'info'
}

const getContestStatusText = (status) => {
  const texts = {
    'upcoming': '即将开始',
    'ongoing': '进行中',
    'ended': '已结束'
  }
  return texts[status] || '未知'
}

const getContestButtonText = (status) => {
  const texts = {
    'upcoming': '报名参加',
    'ongoing': '立即参加',
    'ended': '查看结果'
  }
  return texts[status] || '查看详情'
}

const formatDate = (date) => {
  const now = new Date()
  const diff = now - date
  const days = Math.floor(diff / (1000 * 60 * 60 * 24))
  
  if (days === 0) {
    return '今天'
  } else if (days === 1) {
    return '昨天'
  } else if (days < 7) {
    return `${days}天前`
  } else {
    return date.toLocaleDateString('zh-CN')
  }
}

const formatContestTime = (time) => {
  return time.toLocaleString('zh-CN', {
    month: 'short',
    day: 'numeric',
    hour: '2-digit',
    minute: '2-digit'
  })
}

const goToProblemList = () => {
  router.push('/coding/problems')
}

const goToMySubmissions = () => {
  router.push('/coding/submissions')
}

const goToLeaderboard = () => {
  router.push('/coding/leaderboard')
}

const startRandomProblem = () => {
  // 随机选择一个题目
  const randomId = Math.floor(Math.random() * 1000) + 1
  router.push(`/coding/problem/${randomId}`)
}

const viewAllProblems = () => {
  router.push('/coding/problems')
}

const viewProblem = (problem) => {
  router.push(`/coding/problem/${problem.id}`)
}

const solveProblem = (problem) => {
  router.push(`/coding/editor/${problem.id}`)
}

const viewAllPaths = () => {
  ElMessage.info('学习路径功能开发中...')
}

const viewPath = (path) => {
  ElMessage.info(`查看学习路径：${path.title}`)
}

const viewAllSubmissions = () => {
  router.push('/coding/submissions')
}

const viewSubmission = (submission) => {
  ElMessage.info(`查看提交：${submission.problemTitle}`)
}

const retryProblem = (submission) => {
  router.push(`/coding/editor/${submission.problemId || 1}`)
}

const viewAllContests = () => {
  ElMessage.info('编程竞赛功能开发中...')
}

const joinContest = (contest) => {
  ElMessage.success(`${contest.status === 'upcoming' ? '报名' : '参加'}竞赛：${contest.title}`)
}

onMounted(() => {
  // 初始化数据
})
</script>

<style lang="scss" scoped>
.coding-home {
  min-height: 100vh;
  background: var(--el-bg-color-page);
}

.welcome-banner {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 60px 0;
}

.banner-content {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  
  @media (max-width: 768px) {
    flex-direction: column;
    gap: 30px;
    text-align: center;
  }
}

.welcome-text {
  h1 {
    font-size: 3rem;
    font-weight: 700;
    margin-bottom: 16px;
  }
  
  p {
    font-size: 1.25rem;
    opacity: 0.9;
  }
}

.banner-stats {
  display: flex;
  gap: 40px;
  
  @media (max-width: 768px) {
    gap: 20px;
  }
}

.stat-item {
  text-align: center;
  
  .stat-number {
    font-size: 2rem;
    font-weight: 700;
    margin-bottom: 4px;
  }
  
  .stat-label {
    font-size: 0.9rem;
    opacity: 0.8;
  }
}

.quick-actions {
  max-width: 1200px;
  margin: -30px auto 60px;
  padding: 0 20px;
  position: relative;
  z-index: 10;
}

.action-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 20px;
}

.action-card {
  background: white;
  padding: 30px 24px;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  gap: 20px;
  
  &:hover {
    transform: translateY(-4px);
    box-shadow: 0 8px 30px rgba(0, 0, 0, 0.15);
  }
  
  .action-icon {
    width: 60px;
    height: 60px;
    background: var(--el-color-primary-light-9);
    border-radius: 12px;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-shrink: 0;
    
    .el-icon {
      font-size: 28px;
      color: var(--el-color-primary);
    }
  }
  
  .action-content {
    h3 {
      font-size: 18px;
      font-weight: 600;
      margin-bottom: 8px;
      color: var(--el-text-color-primary);
    }
    
    p {
      font-size: 14px;
      color: var(--el-text-color-secondary);
      margin: 0;
    }
  }
}

.featured-problems,
.learning-paths,
.recent-submissions,
.coding-contests {
  max-width: 1200px;
  margin: 0 auto 60px;
  padding: 0 20px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
  
  h2 {
    font-size: 24px;
    font-weight: 600;
    color: var(--el-text-color-primary);
  }
}

.problems-grid,
.paths-grid,
.contests-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 24px;
}

.problem-card,
.path-card,
.contest-card {
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
  cursor: pointer;
  transition: all 0.3s ease;
  
  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.12);
  }
}

.problem-header,
.contest-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.problem-tags {
  display: flex;
  gap: 6px;
}

.problem-title,
.path-title,
.contest-title {
  font-size: 18px;
  font-weight: 600;
  margin-bottom: 8px;
  color: var(--el-text-color-primary);
}

.problem-desc,
.path-desc,
.contest-desc {
  font-size: 14px;
  color: var(--el-text-color-secondary);
  margin-bottom: 16px;
  line-height: 1.5;
}

.problem-meta,
.contest-meta {
  display: flex;
  gap: 16px;
  margin-bottom: 20px;
  flex-wrap: wrap;
}

.meta-item {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 12px;
  color: var(--el-text-color-placeholder);
  
  .el-icon {
    color: var(--el-color-primary);
  }
}

.problem-footer,
.contest-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.path-icon {
  width: 48px;
  height: 48px;
  background: var(--el-color-primary-light-9);
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 16px;
  
  .el-icon {
    font-size: 24px;
    color: var(--el-color-primary);
  }
}

.path-progress {
  .progress-info {
    display: flex;
    justify-content: space-between;
    margin-bottom: 8px;
    font-size: 12px;
    color: var(--el-text-color-secondary);
  }
}

.submissions-list {
  background: white;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
}

.submission-item {
  display: flex;
  align-items: center;
  padding: 20px 24px;
  border-bottom: 1px solid var(--el-border-color-extra-light);
  
  &:last-child {
    border-bottom: none;
  }
  
  .submission-info {
    flex: 1;
    
    .problem-name {
      font-weight: 500;
      margin-bottom: 4px;
      color: var(--el-text-color-primary);
    }
    
    .submission-time {
      font-size: 12px;
      color: var(--el-text-color-placeholder);
    }
  }
  
  .submission-details {
    display: flex;
    align-items: center;
    gap: 16px;
    margin-right: 20px;
    
    .language {
      font-size: 12px;
      color: var(--el-text-color-secondary);
    }
    
    .status {
      font-size: 12px;
      font-weight: 500;
      
      &.success {
        color: var(--el-color-success);
      }
      
      &.error {
        color: var(--el-color-danger);
      }
      
      &.warning {
        color: var(--el-color-warning);
      }
    }
    
    .runtime {
      font-size: 12px;
      color: var(--el-text-color-placeholder);
    }
  }
  
  .submission-actions {
    display: flex;
    gap: 8px;
  }
}

@media (max-width: 768px) {
  .action-card {
    flex-direction: column;
    text-align: center;
    
    .action-content {
      text-align: center;
    }
  }
  
  .problems-grid,
  .paths-grid,
  .contests-grid {
    grid-template-columns: 1fr;
  }
  
  .submission-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
    
    .submission-details {
      margin-right: 0;
      width: 100%;
      justify-content: space-between;
    }
    
    .submission-actions {
      width: 100%;
      justify-content: flex-end;
    }
  }
}
</style>
